import { login, getInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '../utils/auth'

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: {},
    loadMenus: false
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      console.log('login now')
      setToken(userInfo.token, true)
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      console.log('get user infos')
    },
    // logout
    LogOut ({ commit }) {
      console.log('logout now')
    },
    // 更新菜单
    UpdateMenus ({ commit }) {
      console.log('update menus now')
    }
  }

}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  commit('SET_ROLES', [])
  removeToken()
}

export const setUserInfo = (res, commit) => {
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.roles.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    commit('SET_ROLES', res.roles)
  }
  commit('SET_USER', res)
}

export default user
